﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using VANAD.WindowsLive.Writer.InsertFavoritePlugin.BO;

namespace VANAD.WindowsLive.Writer.InsertFavoritePlugin.UI
{
    public partial class SelectFavoriteDialogForm : Form
    {
        private Favorite _favorite;
        private TreeNode _lastSelectedNode;
        private DirectoryInfo _diFavorites;
        private List<FavoriteDisplayPattern> _displayPatterns;

        // Properties
        public Favorite FavoriteToInsert
        {
            get { return _favorite; }
        }

        public TreeNode LastSelectedNode
        {
            get { return _lastSelectedNode; }
        }

        // Methods
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="LastSelectedNode">This node will be expanded when it's not null.</param>
        public SelectFavoriteDialogForm(string LastSelectedNodeName)
        {
            InitializeComponent();

            _diFavorites = new DirectoryInfo(Environment.GetFolderPath(Environment.SpecialFolder.Favorites));
            
            this.FillPatterns();
            this.AddFavorites();

            foreach (TreeNode node in tvFavorites.Nodes.Find(LastSelectedNodeName, true))
                ExpandTreeNodePath(node);
        }

        /// <summary>
        /// Expand all nodes based on the path from the rootnode to the node.
        /// </summary>
        /// <param name="node">Expand this node and all parent nodes.</param>
        private void ExpandTreeNodePath(TreeNode node)
        {
            if (node.Parent != null)
                ExpandTreeNodePath(node.Parent);
            node.Expand();
        }

        private void FillPatterns()
        {
            _displayPatterns = new List<FavoriteDisplayPattern>();
            FavoriteDisplayPattern pattern;

            pattern = new FavoriteDisplayPattern();
            pattern.Pattern = @"{0} (<a title='{0}' href='{1}'>{1}</a>)";
            pattern.Name = "Fullname and Link";
            pattern.Description = string.Empty;
            _displayPatterns.Add(pattern);

            pattern = new FavoriteDisplayPattern();
            pattern.Pattern = @"<a title='{0}' href='{1}'>{1}</a>";
            pattern.Name = "Only Link";
            pattern.Description = string.Empty;
            _displayPatterns.Add(pattern);

            pattern = new FavoriteDisplayPattern();
            pattern.Pattern = @"<a title='{0}' target='_blank' href='{1}'>{1}</a>";
            pattern.Name = "Only Link (open in new Window)";
            pattern.Description = string.Empty;
            _displayPatterns.Add(pattern);

            cbDisplayPattern.DataSource = _displayPatterns;
            cbDisplayPattern.DisplayMember = "Name";
            cbDisplayPattern.ValueMember = "Pattern";
        }

        private void AddFavorites()
        {
            this.tvFavorites.Nodes.Clear();

            TreeNode node = new TreeNode("Favorites");
            node.Expand();

            //this.contextMenuStrip = new ContextMenuStrip();
            //ToolStripMenuItem item = new ToolStripMenuItem("Refresh");
            //item.Image = this.image;
            //item.Click += new EventHandler(this.contextMenuItem_Click);
            //item.MouseLeave += new EventHandler(this.contextMenuItem_MouseLeave);
            //this.contextMenuStrip.Items.Add(item);
            //node.ContextMenuStrip = this.contextMenuStrip;

            this.tvFavorites.Nodes.Add(node);
            this.itterateFavoritesDirectories(_diFavorites, node);
        }

        private void itterateFavoritesDirectories(DirectoryInfo di, TreeNode parentNode)
        {
            DirectoryInfo[] directories = di.GetDirectories();
            for (int i = 0; i < directories.Length; i++)
            {
                TreeNode node = parentNode.Nodes.Add(directories[i].Name, directories[i].Name);
                this.getFiles(directories[i].GetFiles("*.url"), node);
                this.itterateFavoritesDirectories(directories[i], node);
            }
        }

        private void getFiles(FileInfo[] fi, TreeNode node)
        {
            for (int i = 0; i < fi.Length; i++)
            {
                node.Nodes.Add(this.makeFileNode(fi[i]));
            }
        }

        private TreeNode makeFileNode(FileInfo fi)
        {
            string displayName = fi.Name.Replace(fi.Extension, "");
            TreeNode node = new TreeNode(displayName);
            node.Name = displayName;
            node.Tag = fi;
            return node;
        }

        private void btCancel_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
            this.Close();
        }

        private void btInsertLink_Click(object sender, EventArgs e)
        {
            this.InsertLink();
        }

        private void InsertLink()
        {
            if (tvFavorites.SelectedNode != null && tvFavorites.SelectedNode.Tag != null)
            {
                FileInfo tag = (FileInfo)tvFavorites.SelectedNode.Tag;
                _favorite = new Favorite(tag, cbDisplayPattern.SelectedValue.ToString());
                _lastSelectedNode = tvFavorites.SelectedNode;
                
                this.DialogResult = DialogResult.OK;
                this.Close();
            }
            else
            {
                MessageBox.Show("Please select a link.", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        private void tvFavorites_NodeMouseDoubleClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            if (e.Node.Tag != null)
                this.InsertLink();
        }

        private void tvFavorites_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            if (e.Node.Tag == null)
                e.Node.Expand();
            else
                this.SetExampleText();
        }

        private void cbDisplayPattern_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.SetExampleText();
        }

        private void SetExampleText()
        {
            if (tvFavorites.SelectedNode != null && tvFavorites.SelectedNode.Tag != null)
                _favorite = new Favorite((FileInfo)tvFavorites.SelectedNode.Tag, cbDisplayPattern.SelectedValue.ToString());

            if (_favorite != null)
                lbExampleText.Text = string.Format("Example: {0}", _favorite.DisplayPatternNoHTMLMarkup);
        }

        private void tvFavorites_AfterSelect(object sender, TreeViewEventArgs e)
        {
            this.SetExampleText();
        }
    }
}
